<template>
  <view class="container">
    <view class="comment" v-for="(item, index) in data" :key="index">
      <view class="comment-header">
        <image
          class="comment-avatar"
          :src="
            item.avatar
              ? item.avatar
              : 'https://www.kimhiz.asia/uploads/Avatar-default.jpg'
          "
          mode="scaleToFill"
        />
        <view class="comment-name">{{ item.nickname }}</view>
        <view class="comment-time">{{ formatDateTime(item.createTime) }}</view>

        <view
          class="comment-to"
          @tap="Refresh ? null : toCommentDetail(item)"
          v-if="props.id == 0"
        >
          <uni-icons type="right" color="#555" size="24" />
        </view>
      </view>

      <MoteLines :dt="item.content" :line="2"></MoteLines>
      <view class="comment-image" v-if="item.media_urls">
        <image
          v-for="(img, index) in item.media_urls"
          :key="index"
          :src="img"
          mode="scaleToFill"
          @tap="previewImage(item.media_urls, index)"
        />
      </view>
      <view class="recovery-area-text" @tap="RecoveryComment(item, index)"
        >回复</view
      >
      <view
        class="recovery-area"
        v-if="item.children.length > 0"
        :class="item.isExpanded ? 'active' : ''"
      >
        <StChildComment
          v-for="comment in item.children"
          :key="comment.id"
          :comments="comment"
          :fromName="''"
        ></StChildComment>
      </view>
      <view
        class="toggle-recovery"
        v-if="item.children.length > 0"
        @tap="item.isExpanded = !item.isExpanded"
        >点击{{ item.isExpanded ? "收起" : "展开" }}全部评论<uni-icons
          :type="item.isExpanded ? 'up' : 'down'"
          color="#555"
          size="18"
      /></view>
    </view>
    <uni-popup
      ref="recoveryPopup"
      type="bottom"
      :style="{
        height: offsetHeight > 0 ? offsetHeight + 100 + 'px' : '0',
      }"
      background-color="#fff"
      ><view class="recovery-popup">
        <view class="recovery-input"
          ><uni-easyinput
            v-model="recoveryContent"
            type="text"
            placeholder="请输入回复内容"
            :maxlength="-1"
            :focus="true"
        /></view>
        <view class="recovery-btn" @tap="addRecoverComment">回复</view>
      </view></uni-popup
    >

    <uni-load-more :status="moreStatus" />
  </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import MoteLines from "./MoteLinesDivide.vue";
import { getCommentDataAPI, addRecoverCommentAPI } from "@/services/index";
import { formatDateTime } from "@/utils/time";
import type { CommentData } from "@/services/type";
import { useMemberStore } from "@/stores";

const member = useMemberStore();
let moreStatus = ref<UniHelper.UniLoadMoreStatus>("more");

const props = defineProps({
  id: { type: Number, default: 0 },
  Refresh: { type: Boolean, default: false },
  params: { type: Object as () => CommentData, default: () => ({}) },
});

let data = ref<any>([]);
let recoveryPopup = ref();
let recoveryContent = ref("");
let recoveryParams = ref({});
let offsetHeight = ref(0);
const RecoveryComment = (item: any, index: number) => {
  if (member.profile) {
    recoveryPopup.value.open();
    uni.onKeyboardHeightChange((res) => {
      offsetHeight.value = res.height;
    });
    recoveryParams.value = {
      userId: member.profile.user_id,
      parentId: item.id,
    };
    currentItem.value = item;
    current.value = index;
  } else {
    uni.showToast({
      title: "请先登录",
      icon: "error",
    });
  }
};
let currentItem = ref<any>();
let current = ref<number>(338);
const addRecoverComment = async () => {
  const params = Object.assign(recoveryParams.value, {
    content: recoveryContent.value,
  });
  let result: any = await addRecoverCommentAPI(params);
  if (result.code == 200) {
    result.data.children = [];

    data.value[current.value].children.unshift(result.data);
    currentItem.value.isExpanded = true;
    recoveryPopup.value.close();
    recoveryContent.value = "";
    uni.showToast({
      title: "回复成功",
      icon: "success",
    });
  } else {
    uni.showToast({
      title: "回复失败",
      icon: "error",
    });
  }
};
const previewImage = (urls: [], index: number) => {
  uni.previewImage({
    urls,
    current: index,
    showmenu: true,
  });
};

// 分页参数
let pageParams: any = {
  page: 1,
  limit: 5,
};
const initCommentData = async () => {
  pageParams.page = 1;
  // 分页
  let result: any = await getCommentDataAPI({
    page: 1,
    limit: pageParams.limit,
    userId: "",
    type: "",
    typeId: 0,
  });
  if (result.code == 200) {
    // 遍历评论数据，为每个评论对象添加 isExpanded 属性
    const commentsWithExpanded = result.data.map((comment: any) => {
      return {
        ...comment,
        isExpanded: false, // 默认设置为 false
      };
    });
    data.value = commentsWithExpanded;
    console.log(data.value);
    if (result.pages > 1) {
      moreStatus.value = "more";
      pageParams.page = 1;
    } else {
      moreStatus.value = "noMore";
    }
    return 200;
  } else {
    uni.showToast({
      title: "获取评论失败",
      icon: "error" || "fail",
    });
    return 500;
  }
};
const getCommentList = async () => {
  if (moreStatus.value == "noMore") {
    return uni.showToast({
      title: "没有更多了",
      icon: "error" || "fail",
    });
  }
  moreStatus.value = "loading";

  let params = Object.keys(props.params).length
    ? props.params
    : {
        page: pageParams.page + 1,
        limit: pageParams.limit,
        userId: "",
        type: "",
        typeId: 0,
      };

  let result: any = await getCommentDataAPI(params);
  if (result.code == 200) {
    // 遍历评论数据，为每个评论对象添加 isExpanded 属性
    const commentsWithExpanded = result.data.map((comment: any) => {
      return {
        ...comment,
        isExpanded: false, // 默认设置为 false
      };
    });
    data.value.push(...commentsWithExpanded);

    if (++pageParams.page < result.pages) {
      moreStatus.value = "more";
      // pageParams.page++;
    } else {
      moreStatus.value = "noMore";
    }
    return 200;
  } else {
    uni.showToast({
      title: "获取评论失败11",
      icon: "error" || "fail",
    });
    return 500;
  }
};

const toCommentDetail = (item: any) => {
  if (item.food_id) {
    uni.navigateTo({
      url: `/pages/detail/detail?id=${item.food_id}&type=food`,
    });
  } else if (item.travel_id) {
    uni.navigateTo({
      url: `/pages/detail/detail?id=${item.travel_id}&type=travel`,
    });
  }
};
defineExpose({ getMore: getCommentList, initData: initCommentData });
</script>

<style lang="scss" scoped>
$fontSize: 24rpx;
$imgSize: 165rpx;
.container {
  width: 100%;
  margin-bottom: 10rpx;

  .comment {
    margin: 10rpx 20rpx 0rpx 20rpx;
    background-color: white;
    border-radius: 30rpx;
    padding: 10rpx;
    box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.1);
    .comment-header {
      $avatarSize: 96rpx;
      height: $avatarSize;
      padding: 10rpx;
      display: flex;
      justify-content: left;
      color: #555;
      border-bottom: 1rpx solid #f1f1f1;
      position: relative;

      .comment-avatar {
        overflow: hidden;
        width: $avatarSize;
        height: 100%;
        border-radius: 50%;
      }

      .comment-name {
        position: absolute;
        left: calc($avatarSize + 20rpx);
        font-size: calc($fontSize * 1.2);
      }

      .comment-time {
        flex: 1;
        font-size: $fontSize;
        text-align: right;
        position: absolute;
        bottom: 10rpx;
        left: calc($avatarSize + 20rpx);
      }
      .comment-to {
        position: absolute;
        top: 0;
        right: 20rpx;
        height: 100%;
        width: 100rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .comment-image {
      margin-top: 10rpx;
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      image {
        max-width: calc(98% / 3);
        min-width: calc(98% / 3);
        height: $imgSize;
        border-radius: 5%;
        margin: 5rpx 0;
        box-sizing: border-box;
      }
    }
    .recovery-area-text {
      font-size: calc($fontSize * 1.2);
      color: #999;
      text-align: right;
      padding-right: 20rpx;
    }
    .recovery-area {
      border-top: 1rpx solid #f1f1f1;
      height: 0;
      overflow: hidden;
    }

    .active {
      height: auto;
    }

    .toggle-recovery {
      margin-top: 10rpx;
      font-size: $fontSize;
      color: #999;
      text-align: center;
    }
  }
  .loading-text {
    text-align: center;
    font-size: calc($fontSize * 1.2);
    color: #999;
    padding: 10rpx 0;
  }
  .recovery-popup {
    padding: 10rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .recovery-input {
      flex: 1;
      margin-right: 10rpx;
    }
    .recovery-btn {
      width: 100rpx;
      height: 60rpx;
      background-color: #ffa500;
      border-radius: 30rpx;
      color: white;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
